<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <!--<el-input v-model.trim="listQuery.fcontent" clearable class="filter-item" style="width: 200px;" placeholder="请输入广告编号"/>-->
      <!--<el-select v-model="listQuery.enabled" clearable filterable class="filter-item" placeholder="请选择启用状态">
        <el-option
          v-for="item in fpointOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>-->
      <el-select v-model="listQuery.enabled" clearable style="width: 150px" class="filter-item" placeholder="请选择启用状态">
        <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value"/>
      </el-select>
      <!--<el-select v-model="listQuery.fpointFlag" clearable filterable class="filter-item" placeholder="请选择广告类型">
        <el-option v-for="(key, value) in siteTypeMap" :key="key" :label="key" :value="value"/>
      </el-select>-->
      <!-- v-permission="['sys:ad:read']" -->
      <el-button class="filter-item" :style="{background:buttonColor.lookup,color:buttonColor.color}" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <!-- v-permission="['sys:ad:create']" -->
      <el-button class="filter-item" :style="{background:buttonColor.add,color:buttonColor.color}" icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column :index="indexMethod" align="center" label="序" type="index"/>
      <el-table-column align="center" label="广告标题" prop="fname"/>
      <el-table-column align="center" label="顺序位置" prop="fposition"/>
      <el-table-column align="center" label="广告描述" prop="fcontent"/>
      <el-table-column :formatter="dateFormat" align="center" label="开始时间" prop="fstartTime"/>
      <el-table-column :formatter="dateFormat" align="center" label="结束时间" prop="fendTime"/>
      <!--<el-table-column align="center" label="高度" prop="fpointH"/>
      <el-table-column align="center" label="宽度" prop="fpointW"/>-->
      <el-table-column align="center" label="状态" prop="enabled">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.enabled | statusFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :formatter="dateFormat" align="center" label="修改时间" prop="fupddate"/>
      <!--      <el-table-column align="center" label="操作员" prop="foperator"/>-->

      <el-table-column align="center" width="140" label="操作" class-name="small-padding">
        <template slot-scope="scope">
          <!-- v-permission="['sys:ad:update']" -->
          <el-button :style="{background:buttonColor.edit,color:buttonColor.color}" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <!-- v-permission="['sys:ad:delete']" -->
          <el-button :style="{background:buttonColor.delete,color:buttonColor.color}" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 90%;"><!-- style="width: 600px; margin-left:50px;"-->
        <el-row>
          <el-col :span="10">
            <el-form-item label="广告标题" prop="fname" style="width: 250px">
              <el-input v-model="dataForm.fname"/>
            </el-form-item>
          </el-col>
          <el-col :span="10" style="padding-left: 80px">
            <el-form-item label="链接地址" prop="flink" style="width: 250px">
              <el-input v-model="dataForm.flink"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="顺序位置" prop="fposition" style="width: 250px">
              <el-input v-model="dataForm.fposition"/>
            </el-form-item>
          </el-col>
          <el-col :span="10" style="padding-left: 80px">
            <el-form-item label="广告描述" prop="fcontent" style="width: 250px">
              <el-input v-model="dataForm.fcontent"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="开始时间" prop="fstartTime" style="width: 250px">
              <el-date-picker v-model="dataForm.fstartTime" type="date" style="width: 140px" clearable class="filter-item" placeholder="选择开始日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="10" style="padding-left: 80px">
            <el-form-item label="结束时间" prop="fendTime" style="width: 250px">
              <el-date-picker v-model="dataForm.fendTime" type="date" style="width: 140px" clearable class="filter-item" placeholder="选择结束日期"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="广告图片(2M内)" prop="fpicUrl" style="width: 250px">
              <!--<el-input v-model="dataForm.fpicUrl"/>-->
              <el-upload
                v-model="dataForm.fpicUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :action="uploadPath"
                class="avatar-uploader">
                <img v-if="dataForm.fpicUrl" :src="dataForm.fpicUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"/>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="10" style="padding-left: 80px">
            <el-form-item v-show="dialogStatus=='update'" class="el-form-item-small" label="状态" prop="enabled">
              <el-select v-model="dataForm.enabled" style="width: 150px" class="filter-item" placeholder="请选择状态">
                <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!--<el-form-item label="操作员" prop="foperator">
          <el-input v-model="dataForm.foperator"/>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="createData">确定</el-button>
        <el-button v-else :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listAd, createAd, updateAd, deleteAd } from '@/api/ad'
import { fsiteNoBelongOptions } from '@/api/area'
import Pagination from '@/components/Pagination'
import moment from 'moment'
import { uploadPath } from '@/api/eqtOrder'
import {buttonColor} from '@/filters/index'
const siteTypeMap = {
  0: '室内',
  1: '室外',
  2: '室外总站'
}

const statusMap = {
  0: '禁用',
  1: '启用'
}

export default {
  name: 'Ad',
  components: { Pagination },
  filters: {
    siteTypeFilter(type) {
      return siteTypeMap[type]
    },
    statusFilter(type) {
      return statusMap[type]
    }
  },
  data() {
    return {
      buttonColor:buttonColor,
      uploadPath,
      list: null,
      total: 0,
      fsiteNoBelongOptions: null,
      fpointOptions: null,
      fpointOptions2: null,
      center: '北京',
      lat: 0,
      lng: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        fcontent: undefined,
        fpicUrl: undefined,
        fposition: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      siteTypeMap,
      statusMap,
      dataForm: {
        fid: undefined,
        fcontent: undefined,
        fpicUrl: undefined,
        fname: undefined,
        fposition: undefined,
        fstartTime: undefined,
        fendTime: undefined,
        flink: undefined,
        enabled: undefined,
        fupddate: undefined,
        foperator: undefined
      },
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        fname: [
          { required: true, message: '广告标题不能为空', trigger: 'blur' }
        ],
        fposition: [
          { required: true, message: '顺序位置不能为空', trigger: 'blur' }
        ],
        fpicUrl: [
          { required: true, message: '广告图片不能为空', trigger: 'blur' }
        ],
        // flink: [
        //   { required: true, message: '链接地址不能为空', trigger: 'blur' }
        // ],
        enabled: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ]
      },
      permissionDialogFormVisible: false,
      systemPermissions: null,
      assignedPermissions: null,
      permissionForm: {
        roleId: undefined,
        permIds: []
      }
    }
  },
  created() {
    this.getList()
    fsiteNoBelongOptions(2)
      .then(response => {
        this.fsiteNoBelongOptions = response.data.data.list
      })
  },
  methods: {
    handleAvatarSuccess(res, file) {
      // this.dataForm.fpicUrl = URL.createObjectURL(file.raw)
      this.dataForm.fpicUrl = res.data
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isLt2M // isJPG &&
    },
    formatStatus: function(row, column) {
      return row.enabled === 1 ? '启用' : '禁用'
    },
    dateFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null || date === '') {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    getList() {
      this.listLoading = true
      listAd(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        fid: undefined,
        fcontent: undefined,
        fpicUrl: undefined,
        fname: undefined,
        fposition: undefined,
        fstartTime: undefined,
        fendTime: undefined,
        flink: undefined,
        enabled: undefined,
        fupddate: undefined,
        foperator: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.dataForm.enabled = '1'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    clickMap() {
      // this.resetForm()
      this.dialogFormVisible2 = true
      this.lat = 0
      this.lng = 0
      // this.dataForm.fsiteState = '1'
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createAd(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加教室资料成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.msg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dataForm.enabled = row.enabled.toString()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          debugger
          updateAd(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.fid === this.dataForm.fid) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新管理员成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.msg
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否要删除该广告资料', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAd(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除广告资料成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.msg
            })
          })
      })
    },
    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
